package org.gitman.agentplatform.core;

import java.util.HashMap;
import java.util.Map;

import org.gitman.agentplatform.agent.api.Agent;
import org.gitman.agentplatform.agent.api.AgentFactory;
import org.gitman.agentplatform.core.exceptions.BadArgsException;
import org.gitman.agentplatform.core.services.AgentFactoryRegistrationService;
import org.gitman.agentplatform.ui.api.View;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

/**
 * This class is for managing whole platform, it contains some configuration information. 
 * @author gitman
 *
 */
public class PlatformManager {
	public static long PALY_DELY = 300;
	public static int MAX_ITERATIONS = 1000;
	
	private static PlatformManager instance;
	private BundleContext context;
	private Simulation simulation;
	private View view = null;
	
	private PlatformManager(){
		newSimulation();
	}
	public void setContext(BundleContext context){
		this.context = context;
	}
	public View getView() {
		return view;
	}
	public void setView(View view) {
		this.view = view;
	}
	public void createView(){
		view = new View();
		simulation.setView(view);
	}
	public static PlatformManager getInstatnce(){
		if(instance == null){			
			instance = new PlatformManager();
		}		
		return instance;
	}
	public void newSimulation(){
		simulation = new Simulation(this);
		if(view != null){
			view.update();
		}
	}
	public Simulation getSimulation(){
		return simulation;
	}
	public Map<Class<? extends Agent>, String> getAvailableAgentsInfo(){
		ServiceReference<?> serviceReference = context.getServiceReference(AgentFactoryRegistrationService.class);
		AgentFactoryRegistrationService service = (AgentFactoryRegistrationService) context.getService(serviceReference);
		Map<Class<? extends Agent>, String> map = new HashMap<Class<? extends Agent>, String>();
		for(AgentFactory factory : service.getAgentFactories()){
			map.putAll(factory.getAvailableAgents());
		}		
		return map;
	}
	public Agent getAgentImpl(Class<? extends Agent> clazz, String args) {
		ServiceReference<?> serviceReference = context.getServiceReference(AgentFactoryRegistrationService.class);
		AgentFactoryRegistrationService service = (AgentFactoryRegistrationService) context.getService(serviceReference);
		for(AgentFactory factory : service.getAgentFactories()){
			if(factory.getAvailableAgents().keySet().contains(clazz)){
				try {
					return factory.getAgentImpl(clazz, args);
				} catch (BadArgsException e) {
					e.printStackTrace();
				}
			}
		}		
		return null;
	}
	public Class<? extends Agent> getClassBySimpleName(String name) throws Exception{
		if(name == null){
			throw new Exception("Agent class is not selected");
		}
		for(Class<? extends Agent> clazz : PlatformManager.getInstatnce().getAvailableAgentsInfo().keySet()){
			if(name.equals(clazz.getSimpleName())){
				return clazz;
			}
		}
		return null;
	}
}
